import os
This code is for v1 of the openai package: openai · PyPIpip install openaipip install requestsfrom openai import OpenAIimport base64import requests
my_api_key = os.environ[“OPENAI_API_KEY”]
Function to encode the imagedef encode_image(image_path):with open(image_path, “rb”) as image_file:return base64.b64encode(image_file.read()).decode(‘utf-8’)
Path to your imageimage_path = “.\SourceImages\some_text.jpg”
Getting the base64 stringbase64_image = encode_image(image_path)
Loads a local image file and OCRs it.https://platform.openai.com/docs/guides/visionheaders = {“Content-Type”: “application/json”,“Authorization”: f"Bearer {my_api_key}"}
payload = {“model”: “gpt-4-vision-preview”,“messages”: [{“role”: “user”,“content”: [{“type”: “text”,“text”: “What’s in this image?”},{“type”: “image_url”,“image_url”: {“url”: f"data:image/jpeg;base64,{base64_image}"}}]}],“max_tokens”: 300}
try:
response = requests.post("https://api.openai.com/v1/chat/completions", headers=headers, json=payload)print(response.json())except Exception as ex:print(“Exception:”, ex)